<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑</title>
    <style>

     textarea {
         width: 100%;
         height: 500px;
     }

    </style>
    <script src="/js/jquery.min.js"></script>
    <script src="/js/kindeditor-all-min.js"></script>
</head>
<body>
    
    <textarea id="editor_id" name="content"></textarea>
</body>
<script>
    KindEditor.ready(function(K) {
            window.editor = K.create('#editor_id');
    });

    $(function () {

        var ws = new WebSocket('ws://center.yao-yang.cn:49998/');
        var finish_init = false;
        var html = '';
        var closed = false;

        ws.onmessage = function (event) {
            var res = JSON.parse(event.data);
            editor.html(res.content);
            html = res.content;
            finish_init = true;
        };

        ws.onopen = function () {
            ws.send(JSON.stringify({
                editor: true
            }));
        };

        ws.onclose = function () {
            closed = true;
            if (! finish_init) {
                $.get("/read", function(result){
                    editor.html(result);
                    html = result;
                    finish_init = true;
                });
            }
        };

        setInterval(function () {
            if (finish_init && html !== editor.html()) {
                html = editor.html();
                if (closed) {
                    $.ajax({
                        type: 'POST',
                        url: '/write',
                        data: html
                    });
                } else {
                    ws.send(JSON.stringify({
                        content: html,
                    }));
                }
            }
        }, 1000);
    });

</script>
</html>
